const express = require('express')
const cors = require('cors')
const config = require('./config')  // 配置，解析 token 中间件
const expressJWT = require('express-jwt') 
const userRouter = require('./router/user.js')
const userinfoRouter = require('./router/userinfo.js')
const artCateRouter = require('./router/artcate.js')
const articleRouter = require('./router/article.js')
const commentRouter = require('./router/comment.js')
const lookforRouter = require('./router/lookfor.js')
const getUserinfo = require('./router/getUserinfo.js')	//外来人员获取作者信息
const joi = require('joi')	//快捷表单验证
const FileRouter = require('./router/upload.js')
const VideosRouter = require('./router/images/VideosRouter.js')
const VideoRouter = require('./router/download.js')
const app = express()

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

app.use(cors())
app.use(express.urlencoded({ extended: false }))

app.use('/uploads', express.static('./uploads'))

app.use(function (req, res, next) {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    })
  }
  next()
})
app.use('/api/videos',VideosRouter)

app.use('/api/file',FileRouter);

app.use('/api/video',VideoRouter);

app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] }))

//注意和封装重新挂载的中间件有顺序问题
app.use('/api',articleRouter)	//有个bug

app.use('/api/comment',commentRouter)

app.use('/api',lookforRouter)

app.use('/my/lookfor',lookforRouter);

app.use('/my/comment',commentRouter)

app.use('/api',userRouter)

app.use('/api/Userinfo',getUserinfo)

app.use('/my',userinfoRouter)

app.use('/my',artCateRouter )

app.use('/my/article',articleRouter)

app.use((err,req,res,next)=>{
	if(err instanceof joi.ValidationError) return res.cc(err)
	
	if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
	
	console.log('ERROR!!')
})

app.listen('3007',()=>{
	console.log('我是3007port,running at 3007')
})